<?php

/* 
 * 标题管理 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
class storyTitleController extends AppController
{
    public $class = 'storytitle';
    public function __construct() {
        parent::__construct();
        $this->modelObj = new storyTitleModel();
        $this->log_type = '标题管理';
        $this->title = $this->log_type;
        $this->cookie_key = 'story_title_cookie';
        $this->assign('class', $this->class);
    }
    public function view(){
        $this->_get_data();
        $where = array('is_show' => 1);
        $data = storyModuleModel::load()->getAll(null, $where);      
        $this->assign('module', $data);
        $this->display('title_list');
    }
    public function query(){
        $this->_get_data();
        $this->ret['status'] = 0;
        $this->ret['content'] = $this->fetch('title_list');
        exit(json_encode($this->ret));
    }
    public function fx_tianya(){
        $url = trim($_POST['url']);
        if($url) {
            phpQuery::newDocumentFile($url);
            $bd = pq('#bd');
            $name = $bd->find(".s_title")->text();
            $uid = $bd->find("#post_head")->find(".atl-info a:eq(0)")->attr("uid");
            $author = $bd->find("#post_head")->find(".atl-info a:eq(0)")->attr("uname");
            $stime = $bd->find("#post_head")->find(".atl-info span:eq(1)")->text();        
            $info = array(
                'name' => $name,
                'author' => $author,
                'uid' => $uid,
                'stime' => str_replace('时间：', '', $stime),
            );
            exit($this->setReturn(0, $info));
        }
        exit($this->setReturn(100, 'url 为空'));
    }

    public function create(){
        $this->create_token();
        $this->get_cookie();
        $where = array('is_show' => 1);
        $data = storyModuleModel::load()->getAll(null, $where);      
        $this->assign('module', $data);
        $this->display('title_create');
    }
    public function new_create(){
        
        $this->check_token();
        $data = array(
            'mid' => intval($_POST['mid']),
            'url' => trim($_POST['url']),
            'tname' => trim($_POST['tname']),
            'author' => trim($_POST['author']),
            'uid' => trim($_POST['uid']),
            'stime' => trim($_POST['stime']),//需转换
            'in_time' => p_getTime(),
        );
        $this->set_cookie($data);
        if($data['mid'] <= 0) {
            $this->show_msg('选择模块名称');
        }
        if(empty($data['url'])) {
            $this->show_msg('链接不能为空');
        }
        if(empty($data['tname'])) {
            $this->show_msg('标题不能为空');
        }
        if(empty($data['author'])) {
            $this->show_msg('作者不能为空');
        }
        if(empty($data['uid'])) {
            $this->show_msg('作者ID不能为空');
        }
        if(empty($data['stime'])) {
            $this->show_msg('发表时间不能为空');
        }
        $where = array(
            'tname' => $data['tname'],
        );
        if($this->modelObj->getRow(null, $where)) {
            $this->show_msg('名称重复');
        }
        $data['stime'] = p_str2time($data['stime']);
        $bool = $this->modelObj->insert($data);
        if($bool) {
            $this->admin_log('添加主题' . $data['tname']);
            $this->show_msg('添加成功', 'c=' . $this->class . '&m=view');
        } else {
            $this->show_msg('添加失败');
        }
    }
    public function del(){
        $id = $_POST['id'];
        if($id > 0) {
            if(storyContentModel::load()->getTid($id)) {
                echo $this->setReturn(100, '不能删除，因为在模块里含有数据');exit;
            } else {
                $this->remove();
            }
        }
        echo $this->setReturn(101, '删除失败');
    }
    public function down(){
        $tid = intval($_GET['tid']);
        $type = trim($_GET['type']);
        if($tid > 0) {
            $dir = RES_PATH . 'down/';
            $titleName = storyTitleModel::load()->getName($tid);
            $data = storyContentModel::load()->getContent($tid);
            $file = '';
            switch ($type) {
                case 'txt':
                    $contentStr = '';
                    header( "Content-type: application/octet-stream ");
                    header( "Accept-Ranges: bytes ");
                    header( "Content-Disposition: attachment; filename={$titleName}.txt ");//导出的文件名
                    header( "Expires: 0 ");
                    header( "Cache-Control: must-revalidate, post-check=0, pre-check=0");
                    header( "Pragma: public ");
                    $file = $dir . 'txt/' . date("YmdA") . mt_rand(0, 1000) . '.txt';
                    $contentStr .= "\t\t".$titleName . "\r\n";
                    foreach ($data as $row) {
                        $content = $row['content'];
                        $content =  preg_replace('/<br\\s*?\/??>/i',"\r\n",$content);
                        $content = strip_tags($content);
                        $content .= "\r\n";
                        $contentStr .= $content;
                    }
                    $_titleName = iconv("utf-8","gb2312", $titleName); 
                    $file = $dir . 'txt/' . $_titleName . '.txt';
                    file_put_contents($file, $contentStr);
                    echo $contentStr;
                    break;
                case 'pdf':
                    break;
                default:
                    break;
            }
        }
    }
    /**
     * 来源获取数据
     */
    private function _get_data(){
        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1;  
        $filter['tname'] = isset($_POST['tname']) ? $_POST['tname'] : '';
        $filter['mid'] = isset($_POST['mid']) ? $_POST['mid'] : 0;
        if(!empty($filter['tname'])) {
            $where .= ' and instr(tname, ' . "'{$filter['tname']}')";
        }
        if($filter['mid'] > 0) {
            $where .= ' and sid = ' . $filter['mid'];
        }
        $key = $this->modelObj->keyFields;
        $sort_by = isset($_REQUEST['sort_by']) ? $_REQUEST['sort_by'] : $key;
        $sort_order = isset($_REQUEST['sort_order']) ? $_REQUEST['sort_order'] : 'DESC';
        $pageObj = new pageModel('story_title', $where, $this->page_number, 10, $sort_by, $sort_order);        
        $data = $pageObj->pageData($page);
        $list = $data['pageData'];
        if($list) {
            foreach ($list as $key => $row) {                
                $data['pageData'][$key]['id'] = $key + 1;
                $data['pageData'][$key]['mname'] = storyModuleModel::load()->getName($row['mid']);
                $data['pageData'][$key]['stime_format'] = publicController::load()->friendlyDate($row['stime']);       
                $data['pageData'][$key]['in_time_format'] = publicController::load()->friendlyDate($row['in_time']);               
                $data['pageData'][$key]['is_show'] = $row['is_show'] == 1 ? 'glyphicon-ok' : 'glyphicon-remove';  
            }
        }
        $this->assign('sort_' . $sort_by, $data['sort_img']);
        $this->assign('data', $data);
    }
}

